package my.yuan.fkzservice.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import my.yuan.fkzcommon.ddo.MenuDO;
import my.yuan.fkzcommon.vo.MenuTreeVO;
import my.yuan.fkzmapper.mapper.MenuMapper;
import my.yuan.fkzservice.service.MenuService;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, MenuDO>
        implements MenuService {

    @Override
    public MenuTreeVO tree() {
        MenuDO root = getOne(Wrappers.<MenuDO>lambdaQuery()
                .eq(MenuDO::getCode, "/")
        );
        return recurisiveTree(root);
    }

    private MenuTreeVO recurisiveTree(MenuDO pMenu) {
        List<MenuTreeVO> child = list(Wrappers.<MenuDO>lambdaQuery()
                .eq(MenuDO::getPid, pMenu.getId())
        ).stream()
                .map(this::recurisiveTree)
                .sorted(Comparator.comparing(MenuTreeVO::getSort))
                .collect(Collectors.toList());
        return buildTree(pMenu, child);
    }


    private MenuTreeVO buildTree(MenuDO menu, List<MenuTreeVO> child) {
        return MenuTreeVO.builder()
                .id(menu.getId())
                .name(menu.getName())
                .code(menu.getCode())
                .url(menu.getUrl())
                .type(menu.getType())
                .sort(menu.getSort())
                .level(menu.getLevel())
                .child(child)
                .build();
    }

    public static MenuTreeVO buildTree(MenuDO ddo) {
        if (ddo == null) {
            return null;
        }
        MenuTreeVO menuTreeVO = new MenuTreeVO();
        menuTreeVO.setId(ddo.getId());
        menuTreeVO.setName(ddo.getName());
        menuTreeVO.setCode(ddo.getCode());
        menuTreeVO.setUrl(ddo.getUrl());
        menuTreeVO.setType(ddo.getType());
        menuTreeVO.setSort(ddo.getSort());
        menuTreeVO.setLevel(ddo.getLevel());

        return menuTreeVO;
    }
}




